#!/bin/bash
#This script is used to start|stop|restart Tomcat Server.
#date:2013-12-13 2:58
#chkconfig: 2345 96 14
export PATH=/bin:/usr/bin
. /etc/init.d/functions

U_UID=500
TOMCAT="tomcat_item"

USER=`echo $UID`

if [ $USER == $U_UID ]
then

	TOMCAT_START="/usr/local/$TOMCAT/bin/catalina.sh"

	case "$1" in

	start)

		pidnum=`ps -ef | grep java | grep $TOMCAT | awk '{print $2}' | wc -l`

		if [ $pidnum -eq 0 ]
		
		then
			sleep 2
			action "Starting Tomcat..."  /bin/true
			$TOMCAT_START $1>/dev/null 2>&1
			
		else
			echo -e "\e[31mTomcat is running\e[0m"
		fi
		;;

	stop)
			
		pidnum=`ps -ef | grep java | grep $TOMCAT | awk '{print $2}' | wc -l`
	
		if [ $pidnum -ne 0 ]
		
		then
			sleep 2
			action "Stoping Tomcat..." /bin/true
			$TOMCAT_START $1 >/dev/null 2>&1
			ps -ef | grep java | grep $TOMCAT | awk '{print $2}' | xargs kill -9
		
		else 
			echo -e "\e[31mTomcat is stopped\e[0m"	
		fi
		;;

	restart)

		pidnum=`ps -ef | grep java|grep $TOMCAT| awk '{print $2}' | wc -l`
		if [ $pidnum -eq 0 ]
		then
			sleep 2
			action "Retart Tomcat..."  /bin/true
			$TOMCAT_START start >/dev/null 2>&1
			
		else
			sleep 2
			ps -ef | grep java |grep $TOMCAT | awk '{print $2}' | xargs kill -9
			action "Restart Tomcat..." /bin/true
			$TOMCAT_START start >/dev/null 2>&1
			
		fi
		;;
	*)
		echo
		echo -e "\e[31m	You enter a wrong Parameter,please try again\e[0m"
		echo
		;;
	esac
else
	echo
	echo -e "	Please use 'sudo service tomcat \e[31mstop\e[0m|\e[31mstart\e[0m|\e[31mrestart\e[0m'"
	echo
fi
exit 0

